/* eslint-disable no-undef */
/* eslint-disable no-constant-condition */
/* eslint-disable react/react-in-jsx-scope */
import classnames from 'classnames'
import { useHistory } from 'react-router'
// eslint-disable-next-line no-unused-vars
import { Dialog, NavBar, SearchBar } from 'antd-mobile'

import Icon from '@/components/Icon'
import styles from './index.module.scss'
// import { useRef, useState } from 'react'
import { useDebounceFn } from 'ahooks'
import { useEffect, useState } from 'react'
import { getSuggestion } from '@/store/actions/search'
// import { useDispatch } from 'react-redux'
// import { RootState } from '@/types/store'
// import { useStore } from 'react-redux'
import highLight from '@/components/HighLight'
import { getHistory, setHistory } from '@/utils/storageHistory'
const SearchPage = () => {
  const history = useHistory()
  // const dispatch = useDispatch()
  const [keyword, setKeyword] = useState('')
  // 准备定时器
  //   const timerRef = useRef(-1)
  //   const onChange = async (val:string) => {
  //     // 清空定时器
  //     window.clearTimeout(timerRef.current)
  //     // 新开一个定时器
  //     timerRef.current = window.setTimeout(async () => {
  //       // 发请求，取回搜索建议
  //       const res = await getSuggestion(val)
  //       console.log('val', val, res)
  //     }, 500)
  //   }
  const [searchHistory, setSearchHistory] = useState<string[]>(() => getHistory())
  const [suggestion, setSuggestion] = useState<string[]>([])
  const onChange = async (val:string) => {
    setKeyword(val)
    // const res = await getSuggestion(val)
    // console.log('val', val, res)
    run()
  }
  const { run } = useDebounceFn(async () => {
    // 1.发请求,取回搜索建议
    if (!keyword) {
      setSuggestion([])
      return
    }
    const res = await getSuggestion(keyword)
    const suggestion = res.data.data.options
    // console.log(suggestion)
    setSuggestion(suggestion)
  }, { wait: 500 })
  // const { suggestion, histories } = useSelector((state:RootState) => state.search)
  // console.log(histories, 667)
  // 追加搜索历史记录
  const onSearch = (keyword:string) => {
    console.log('追加历史搜索记录', keyword)
    // 1. 删除现有的
    const index = searchHistory.findIndex(item => item === keyword)
    if (index !== -1) {
      searchHistory.splice(index, 1)
    }
    // 2.追加到第一项
    const newList = [keyword, ...searchHistory]
    setSearchHistory(newList)

    // 3. 跳转页面
    setTimeout(() => {
      history.push('/search/result?keyword=' + keyword)
    }, 100)
  }

  // 清除历史记录
  // const onClearHistory = () => {
  //   Dialog.confirm({
  //     title: '温馨提示',
  //     content: '你确定要清空记录吗？',
  //     onConfirm: function () {
  //       dispatch(clearHistories())
  //     }
  //   })
  // }
  // 清除单个历史记录
  const delSearchHistory = (index:number) => {
    searchHistory.splice(index, 1)
    // 删除之后要记得更新
    setSearchHistory([...searchHistory])
  }
  // 当searchHistory 变化时,做持久化
  useEffect(() => {
    setHistory(searchHistory)
  }, [searchHistory])

  return (
    <div className={styles.root}>
      <NavBar
        className="navbar"
        onBack={() => history.go(-1)}
        // eslint-disable-next-line react/react-in-jsx-scope
        right={<span className="search-text" onClick={() => { onSearch(keyword) }}>搜索</span>}
      >
        <SearchBar value={keyword} onChange={onChange} placeholder="请输入关键字搜索" />
      </NavBar>

      {true && (
        <div
          className="history"
          style={{
            display: false ? 'none' : 'block'
          }}
        >
          <div className="history-header">
            <span>搜索历史</span>
            {/* 清除全部历史记录 */}
            <span onClick={() => setSearchHistory([])}>
              <Icon type="iconbtn_del" />
              清除全部
            </span>
          </div>
         {/* 搜索历史 */}
          <div className="history-list" style={{ display: keyword.length ? 'none' : 'block' }}>
           {searchHistory.map((item, index) => {
             return (
               <span key={index} className="history-item" >
               {index !== 0 && <span onClick={() => onSearch(item)} className="text-overflow ">{item}</span>}
               {index !== 0 && < Icon type="iconbtn_essay_close" onClick={() => { delSearchHistory(index) }}/>}
               </span>)
           })}

          </div>
        </div>
      )}
    {/* 搜索建议结果列表 */}
      <div className={classnames('search-result', { show: keyword.length })}>
        {suggestion.map((str, index) => {
          return (
            <div key={index} className="result-item " >
              {/* 搜索框-放大镜 */}
            <Icon className="icon-search" type="iconbtn_search" />
            <div onClick={() => onSearch(str)} className="result-value text-overflow"
             dangerouslySetInnerHTML={{
               __html: highLight(str, keyword)
             }}
            >
            </div>
          </div>)
        })}

      </div>
    </div>
  )
}

export default SearchPage
